package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.service.IBaseService;
import cn.itsource.basic.util.PageList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

@Transactional
public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery> implements IBaseService<T,Q> {

    @Autowired
    private Mapper<T> mapper;

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public List<T> findAll() {
        return mapper.selectAll();
    }

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
    public T findOne(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(T t) {
        mapper.insertSelective(t);
    }

    @Override
    public void update(T t) {

        mapper.updateByPrimaryKeySelective(t);
    }

    @Override
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageList<T> findPage(Q q) {
        //1.使用分页插件   1,2步中间不能写代码
        PageHelper.startPage(q.getCurrentPage(),q.getPageSize());

        //2.执行查询语句
        List<T> ts = mapper.selectAll();

        //3.封装成一个pageInfo对象（分页插件提供的）
        PageInfo<T> pageInfo = new PageInfo<>(ts);

        //4.返回我们自己定义的PageList对象  total list
        PageList<T> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());

        //返回结果
        return pageList;
    }

    @Override
    public void batchDelete(Q q) {

        //获取到ids,遍历删除
        Long[] ids = q.getIds();
        //健壮性判断
        if (ids != null && ids.length > 0){
            //循环所有的is
            for (Long id : ids) {
                //调用删除功能
                mapper.deleteByPrimaryKey(id);
            }
        }
    }
}
